package com.rtz.util;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;


public class NumberGenerator {

	private static final String CURRENT_DATE = "number.generator.current.date";
	private static final String SERIAL_NUM = "number.generator.serial.num";

	// 单例模式
	private static NumberGenerator numberGenerator = new NumberGenerator();

	private String filePath = "";
	private Properties properties = new Properties();

	// 当前日期
	private String currentDate = "20161014";

	// 序列号
	private int serialNum = 0;

	// 预定的最大值
	@SuppressWarnings("unused")
	private int maxNum = 999999999;

	private NumberGenerator() {
		try {
			this.init();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static NumberGenerator getInstance() {
		return numberGenerator;
	}

	public void init() throws Exception {

		
		
		ClassLoader contextClassLoader = Thread.currentThread()
				.getContextClassLoader();
		this.filePath = contextClassLoader
				.getResource("conf/NumberGenerator.properties").getFile();
		
		InputStream is =  new BufferedInputStream(contextClassLoader
					.getResource("conf/NumberGenerator.properties")
					.openStream());
		this.properties.load(is);

		is.close();
		this.currentDate = this.properties.getProperty(CURRENT_DATE);
		this.serialNum = Integer
				.parseInt(this.properties.getProperty(SERIAL_NUM));
		
	}

	/**
	 * 
	 * @param digit the digit to be generated number.
	 * @return
	 */
	public synchronized String generateSerialNumber(int digit) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String nowDate = sdf.format(new Date());
		
		//TODO: 内存溢出
		if (!nowDate.equals(this.currentDate)) {
			this.serialNum = 0;
			this.currentDate = nowDate;

			try {
				OutputStream fos = new FileOutputStream(this.filePath);
				this.properties.setProperty(CURRENT_DATE, nowDate);
				this.properties.store(fos,"The Date and Serial Number of the last message");
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else {
			
			this.serialNum++;
			try {
				OutputStream fos = new FileOutputStream(this.filePath);
				BufferedWriter bw = new BufferedWriter(
						new OutputStreamWriter(fos, "utf-8"));
				this.properties.setProperty(SERIAL_NUM,
						String.valueOf(this.serialNum));
				this.properties.store(bw,"The Date and Serial Number of the last message sent to HF Bank");
				fos.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		String serialNumStr = String.valueOf(this.serialNum);
		while (serialNumStr.length() < digit) {
			serialNumStr = "0" + serialNumStr;
		}
		
		return serialNumStr;
		
	}

}
